#include "ForceRegistry.h"

std::hash_map<Particle*, std::list<ForceGenerator*>*> 
	ForceRegistry::registry = 
	std::hash_map<Particle*, std::list<ForceGenerator*>*>();
ForceRegistry* ForceRegistry::instance = 0;

ForceRegistry::~ForceRegistry()
{
	clear();
	instance = 0;
}

void ForceRegistry::init()
{
	ForceRegistry::instance = new ForceRegistry();
}

void ForceRegistry::update(float frameTime)
{
	std::hash_map<Particle*, std::list<ForceGenerator*>*>::iterator iter = registry.begin();
	for (; iter != registry.end(); iter++)
	{
		std::list<ForceGenerator*>::iterator listIter = iter->second->begin();
		for (; listIter != iter->second->end(); listIter++)
		{
			(*listIter)->updateForce(iter->first, frameTime);
		}
	}
}

void ForceRegistry::add(Particle* particle, ForceGenerator* force)
{
	std::hash_map<Particle*, std::list<ForceGenerator*>*>::iterator iter = registry.find(particle);
	if (iter == registry.end())
	{
		std::list<ForceGenerator*>* list = new std::list<ForceGenerator*>();
		list->push_back(force);
		registry[particle] = list;
	}
	else
	{
		iter->second->push_back(force);
	}
}

void ForceRegistry::remove(Particle* particle, ForceGenerator* force)
{
	registry[particle]->remove(force);
}

void ForceRegistry::clear()
{
	std::hash_map<Particle*, std::list<ForceGenerator*>*>::iterator iter = registry.begin();
	for (; iter != registry.end(); iter++)
	{
		std::list<ForceGenerator*>::iterator listIter = iter->second->begin();
		for (; listIter != iter->second->end(); listIter++)
		{
			delete *listIter;
			*listIter = 0;
		}
		delete iter->second;
		iter->second = 0;
	}
}